package com.kla.power.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kla.power.entity.ScreenUserEntity;
import com.kla.power.mapper.ScreenUserMapper;
import com.kla.power.service.IScreenUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kla.power.util.SnowflakeIdWorker;
import com.kla.power.util.StateEnum;
import com.kla.power.util.StateException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 大屏用户关联，每位用户可独立设置大屏标题 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2024-08-06
 */
@Service
public class ScreenUserServiceImpl extends ServiceImpl<ScreenUserMapper, ScreenUserEntity> implements IScreenUserService {


    @Override
    public List<ScreenUserEntity> queryList ( ScreenUserEntity screenUserEntity) {
        List<ScreenUserEntity> screenUserEntities = baseMapper.selectList ( new QueryWrapper<ScreenUserEntity> ().eq ( "userId", screenUserEntity.getUserId () ) );
        return screenUserEntities;
    }

    @Override
    public ScreenUserEntity saveSingle (ScreenUserEntity screenUserEntity) {
        screenUserEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( screenUserEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return screenUserEntity;
    }

    @Override
    public ScreenUserEntity updateSingle (ScreenUserEntity screenUserEntity) {
        // 先查询
        ScreenUserEntity screenUser = baseMapper.selectOne ( new QueryWrapper<ScreenUserEntity> ().eq ( "userId", screenUserEntity.getUserId () ).eq ( "screenId", screenUserEntity.getScreenId () ) );
        if ( screenUser == null ) {
            screenUserEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            int insert = baseMapper.insert ( screenUserEntity );
            if ( insert == 0 ) {
                throw new StateException ( StateEnum.INSERT_EXCE );
            }
            return screenUserEntity;
        }
        UpdateWrapper<ScreenUserEntity> updateWrapper = new UpdateWrapper<> ();
        if ( screenUserEntity.getTitle () != null ) {
            updateWrapper.set ( "title", screenUserEntity.getTitle () );
        }
        updateWrapper.eq ( "userId", screenUserEntity.getUserId () ).eq ( "screenId", screenUserEntity.getScreenId () );
        screenUserEntity.setChangeTime ( new Date () );
        int update = baseMapper.update ( null, updateWrapper );
        if ( update == 0 ) {
            throw new StateException ( StateEnum.UPDATE_EXCE );
        }
        return screenUserEntity;
    }

}
